package com.learn.sqlsession;

import com.learn.config.XmlConfigBuilder;
import com.learn.io.Resources;
import com.learn.pojo.Configuration;
import com.learn.sqlsession.impl.DefaultSqlSessionFactory;
import org.dom4j.DocumentException;

import java.beans.PropertyVetoException;
import java.io.InputStream;

/**
 * @author WuLiangHang
 */
public class SqlSessionFactoryBuilder {
    private static SqlSessionFactoryBuilder sqlSessionFactoryBuilder;

    private SqlSessionFactoryBuilder() {
    }

    public static SqlSessionFactoryBuilder getInstance() {
        if (sqlSessionFactoryBuilder == null) {
            sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        }
        return sqlSessionFactoryBuilder;
    }

    public SqlSessionFactory build(InputStream input) throws PropertyVetoException, DocumentException {
        //获取配置文件输入流，配置文件中包含SqlMapper
        //1.读取配置文件并且塞到Configuration中
        //2.读取配置文件中的SQL 塞到MappedStatement中
        Configuration configuration = XmlConfigBuilder.parseConfig(input);
        //创建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        return sqlSessionFactory;
    }
}
